//index.js
const app = getApp()

Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    logged: false,
    takeSession: false,
    requestResult: '',
    family: '',
  },

  onLoad: function() {
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              console.log('res.userInfo', res.userInfo)
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })
            }
          })
        }
      }
    })
    this.loadData()
  },

  onShow(){
    if (app.globalData.refresh) {
      this.loadData()
    }
  },

  loadData(){
    app.globalData.refresh = false;
    app.getMyInfo().then(info => {
      console.log('info---', info)
      if (info && info.relations && info.mine) {
        const c = info.mine.code
        const family = Object.values(info.relations)
        .filter(x => x.a === c)
        .map(x=> ({a: x.a ,b: x.b, code: x.code, name: info.members[x.b].name}))
        console.log('aaaaa', family)
        this.setData( { family, info })  
      }
    })
  },

  mine(){
    wx.redirectTo({
      url: '../jiusi/two/two'
    })
  },

  onGetUserInfo: function(e) {
    if (!this.data.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      })
    }
  },

  onGetOpenid: function() {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },
})
